package tongkeyon.create.prototype.improve;

import java.io.*;

/**
 * @Author: keyon <tongkeyon@163.com>
 * @Date: 2020/2/18 11:18
 * @Version 1.0
 */
public class Sheep2 implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    private Sheep1 friend;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Sheep1 getFriend() {
        return friend;
    }

    public void setFriend(Sheep1 friend) {
        this.friend = friend;
    }

    public Sheep2(String name, int age, Sheep1 friend) {
        this.name = name;
        this.age = age;
        this.friend = friend;
    }

    //重写clone方法只能处理类中全为基本数据类型的类
    //对于含有引用数据类型的类来说这种操作太麻烦
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Sheep2 sheep2 = (Sheep2) super.clone();
        sheep2.getFriend().clone();
        return sheep2;
    }



    //可以借由序列化和反序列化操作，会将对象进行深度复制，要求当前类，和当前类的引用类型属性要实现Serializable
    public Object copy() throws IOException, ClassNotFoundException {
        //序列化

            //获得字节输出流,本质是获得缓冲区(该IO流中存在着一个缓存区，可以将序列化的数据放入此缓冲区中，否则要将序列化的数据保存为本地文件)
       ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            //将对象流与缓冲区绑定
       ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
           //进行序列化操作,将当前对象转化为二进制流写到缓冲区中
       objectOutputStream.writeObject(this);


        //反序列化

          //将字节输出流缓冲区中的数据保存到字节数组输入流的缓冲区中
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Object object = objectInputStream.readObject();
        return object;

    }


    @Override
    public String toString() {
        return "Sheep2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", friend=" + friend +
                '}';
    }
}
